package rsj.api.user;

import com.rlyy.aibase.db.Dbink;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import common.util.Assert;
import common.util.BoxUtil;
import common.util.emailUtils.EmailMessage;
import common.util.emailUtils.EmailUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.dao.UserInfoDao;
import rsj.db.PostgresqlConn;
import rsj.utils.RedisUtils;

import java.sql.Connection;
import java.util.Objects;

/**
 * @author yuanqinglong
 * @since 2020/10/16 11:12
 */
@RestController
public class SendMessage extends BaseLink {

    private static final UserInfoDao INFO_DAO = UserInfoDao.getInstance();

    @Override
    @RequestMapping(value = "rsj_pub_sso_sendEmail")
    public Box executeLink(Box box) {
        MapNode data = box.getMapNode("data");
        String tid = box.getNode("$tid");
        String userEmail = data.getValue("user_email");
        String emailType = data.getValue("email_type");
        String userUname = data.getValue("user_uname");
        Assert.isNotBlank(userUname, "账号为空");
        Assert.isNotBlank(userEmail, "邮箱地址不可为空");
        Assert.isNotBlank(emailType, "邮箱类型不可为空");
        Connection connection = PostgresqlConn.getConnection();
        try {
            MapNode userByUserName = INFO_DAO.getUserByUserName(connection, userUname);
            if (userByUserName.size() == 0 || !Objects.equals(userUname, userByUserName.getValue("User_Uname"))) {
                return BoxUtil.errorBox(box, "用户名不存在");
            }
            if (!Objects.equals(userByUserName.getValue("User_Email"), userEmail)) {
                return BoxUtil.errorBox(box, "邮箱不匹配请核对");
            }
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.setReceiveMailAccount(userEmail);
            emailMessage.setRecipient(userEmail);
            String sms = String.format("rsj:%s:%s", emailType, userEmail);
            String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
            // 找回密码
            if (Objects.equals("01", emailType)) {
                emailMessage.setSubject("融数据-找回密码");
                emailMessage.setContent("验证码为:" + code + ", 有效时间: 10分钟");
            }
            // 修改邮箱
            if (Objects.equals("02", emailType)) {
                emailMessage.setSubject("融数据-修改邮箱");
                emailMessage.setContent("");
            }
//        JedisUtil.set(sms, code, 600000, tid);
            RedisUtils.set(sms, code, 600);
            EmailUtil.sendMail(emailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return BoxUtil.errorBox(box, "发送失败");
        } finally {
            Dbink.close(connection);
        }
        return BoxUtil.successBox(box, "发送成功");
    }
}
